package com.xingda.packing.dmss.rabbitmq.config;

import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory.ConfirmType;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConnFactory {


    /**
     * 报警
     */
    @Bean(name = "alarmConnectionFactory")
    public ConnectionFactory alarmConnectionFactory(
            @Value("${spring.rabbitmq.alarm-mq.host:127.0.0.1}") String host,
            @Value("${spring.rabbitmq.alarm-mq.port:5672}") int port,
            @Value("${spring.rabbitmq.alarm-mq.username:admin}") String username,
            @Value("${spring.rabbitmq.alarm-mq.password:admin}") String password,
            @Value("${spring.rabbitmq.alarm-mq.virtual-host:/}") String virtualHost,
            @Value("${spring.rabbitmq.alarm-mq.publisher-confirms:true}") boolean publisherConfirms
    ) {
        return connectionFactory(host, port, username, password, virtualHost, publisherConfirms);
    }


    @Bean(name = "alarmRabbitTemplate")
    public RabbitTemplate secondRabbitTemplate(@Qualifier("alarmConnectionFactory") ConnectionFactory connectionFactory) {
        return new RabbitTemplate(connectionFactory);
    }


    @Bean(name = "alarmFactory")
    public SimpleRabbitListenerContainerFactory alarmFactory(
            SimpleRabbitListenerContainerFactoryConfigurer configurer,
            @Qualifier("alarmConnectionFactory") ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        configurer.configure(factory, connectionFactory);
        return factory;
    }

    private CachingConnectionFactory connectionFactory(String host, int port, String username, String password, String virtualHost, boolean publisherConfirms) {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(virtualHost);
        if (publisherConfirms) {
            connectionFactory.setPublisherConfirmType(ConfirmType.CORRELATED);
        }
        return connectionFactory;
    }
}
